# -*- coding: utf-8 -*-

import contextlib
import datetime

from urllib import parse
from sqlalchemy import create_engine, Column, DateTime, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from com.maycur import config_loader


# MySQL配置
mysql_config = config_loader.get_mysql_config()
url = mysql_config.url
db_name = mysql_config.db_name
user_name = mysql_config.user_name
pwd = mysql_config.password
# 将密码中的@转换为特殊密码
pwd = parse.quote_plus(pwd)


# 初始化数据库连接
connection_str = f'mysql+pymysql://{user_name}:{pwd}@{url}/{db_name}'
print(connection_str)
engine = create_engine(connection_str, encoding='utf-8', echo=True)


Session = sessionmaker(bind=engine, expire_on_commit=False)
# 对象的基类
Base = declarative_base()


@contextlib.contextmanager
def get_session():
    s = Session()
    try:
        yield s
        s.commit()
    except Exception as e:
        s.rollback()
        raise e
    finally:
        s.close()


class BaseCreateOperationEntity:
    created_at = Column(DateTime, nullable=False, default=datetime.datetime.now)
    created_by = Column(String, nullable=False, default='')


class BaseOperationEntity(BaseCreateOperationEntity):
    updated_at = Column(DateTime, nullable=False)
    updated_by = Column(String, nullable=False)
